package common;

import java.security.*;
import java.security.spec.*;

public class SignatureCreator {
	PrivateKey privateKey;
	Signature dsa;

	public SignatureCreator(byte[] encodedKey){
		initPrivateKey(encodedKey);
		createSignature();
	}

	/**
	 * create a Signature object and initialize it with the private key
	 */
	private void createSignature() {
		try{
		this.dsa = Signature.getInstance("SHA1withDSA", "SUN");
		this.dsa.initSign(this.privateKey);
		} catch (Exception e) {
			System.err.println("Caught exception " + e.toString());
			e.printStackTrace();
		}
	}

	/**
	 * initializing the private key
	 * @param encodedKey
	 */
	private void initPrivateKey(byte[] encodedKey) {
		// create a key factory
		KeyFactory keyFactory;
		try {		
			keyFactory = KeyFactory.getInstance("DSA", "SUN");
		// create the privateKey according to the imported
		PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedKey);
		this.privateKey = keyFactory.generatePrivate(privateKeySpec);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchProviderException e) {
			e.printStackTrace();
		} catch (InvalidKeySpecException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @param byteArrToSign- data to sign
	 * @return byte array representation of the signature
	 * @throws SignatureException
	 */
	public byte[] sign(byte[] byteArrToSign) throws SignatureException {
		updateSignature(byteArrToSign);
		return this.dsa.sign();
	}


	/**
	 * add the given data to the signature object
	 * @param data- the data to add to the signature object
	 */
	public void updateSignature(byte[] dataToVerify){
		int offset = 0;
		int bytesLeft;
		bytesLeft = dataToVerify.length;
		while (bytesLeft > 0){
			if (bytesLeft > 1024){
				try {
					this.dsa.update(dataToVerify, offset, 1024);
				} catch (SignatureException e) {
					System.err.println("Caught exception " + e.toString());
					e.printStackTrace();
				}
				offset += 1024;
				bytesLeft -= 1024;
			} else {
				try {
					this.dsa.update(dataToVerify, offset, bytesLeft);
				} catch (SignatureException e) {
					System.err.println("Caught exception " + e.toString());
					e.printStackTrace();
				}
				offset += bytesLeft;
				bytesLeft = 0;
			}		
		}
	}
}




